/**
 * 
 */
package any.tag.server.resource;

import javax.activation.FileTypeMap;

import org.apache.commons.lang.StringUtils;
import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import any.restlet.helper.RepresentationHelper;
import any.tag.server.TagService;

/**
 * Resource of all tags
 * 
 * @author keke <keke@codehaus.org>
 * @version
 * @revision $Revision:$
 */
public class TagsResource extends Resource {
    private static final Logger  LOG = LoggerFactory
                                             .getLogger(TagsResource.class);
    private RepresentationHelper repHelper;
    private TagService           tagService;
    private String               type;

    @Override
    public void init(final Context context, final Request request,
            final Response response) {
        super.init(context, request, response);
        type = (String) request.getAttributes().get("type");
        if (StringUtils.isEmpty(type)) {
            type = "html";
        }
        setAvailable(true);
        setReadable(true);
        setModifiable(false);
        getVariants().add(
                new Variant(MediaType
                        .valueOf(FileTypeMap.getDefaultFileTypeMap()
                                .getContentType("this." + type))));
    }

    @Override
    public Representation represent(final Variant variant)
            throws ResourceException {
        final Representation rep = repHelper.toRepresentation("tags",
                tagService.getAllTags(), variant);
        if (rep == null) {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE,
                    "Type " + variant.getMediaType());
        }
        return rep;
    }

    public void setRepHelper(final RepresentationHelper repHelper) {
        this.repHelper = repHelper;
    }

    public void setTagService(final TagService tagService) {
        this.tagService = tagService;
    }

}
